var mongoose = require("./db");
var movies = new mongoose.Schema({
    title: String,
    plot: String,
    rating: String,
    runtime: String,
    genre: String,
    cast: [String],
    info: { director: String, yearReleased: Number }


})
var Movies = mongoose.model("movies", movies);
const moviesData = ["title", "plot", "rating", "runtime", "genre", "cast", "info"]


Movies.create = async function () {
    let data = Array.from(arguments)
    let saveForm = {}
    data.forEach((item, index) => {
        saveForm[moviesData[index]] = item
    })
    let movies = new Movies(saveForm)
    const result = await movies.save()
    return result
}

Movies.getAll = async function () {
    let result = await Movies.find()
    return result
}
Movies.get = async function (id) {
    let result = await Movies.findOne({ _id: id })
    return result
}
Movies.remove = async function (id) {
    try {
        let title = await Movies.findOne({ _id: id })
        if (title) {
            let result = await Movies.deleteOne({ _id: id })
            return `${title.title} all delete success`
        } else {
            throw new Error("id is not undefind")
        }

    } catch (err) {
        return err
    }

}
Movies.rename = async function (id, title) {
    try {
        let result = await Movies.findOne({ _id: id })
        result.title = title
        return await result.save()

    } catch (err) {
        return err
    }
}
module.exports = Movies;